<template>
  <div v-if="usersPage">
    <PaginationBar
      :currentPage="currentPage"
      :lastPage="usersPage.pages"
      :urlBase="urlBase"
    ></PaginationBar>
    <TableUser
      :users="usersPage.items"
      @filter-update="updateHandler"
    ></TableUser>
  </div>
  <div v-else-if="error != ''">
    <h3 class="text-danger">{{ error }}</h3>
  </div>
  <div v-else>
    <div class="spinner-border text-primary" role="status">
      <span class="visually-hidden">Loading...</span>
    </div>
  </div>
</template>
  
  <script>
import TableUser from "../components/TableUser.vue";
import PaginationBar from "../components/PaginationBar.vue";
import { useFetch } from "@vueuse/core";

export default {
  components: {
    TableUser,
    PaginationBar,
  },
  props: {
    tokens: Object,
    user: Object,
    currentPage: Number,
    urlBase: String,
    customFilterParams: {
      type: Object,
      default: function () {
        return {};
      },
    }, // apply after filterParams and can overwrite it
  },
  data() {
    return {
      usersPage: undefined,
      error: "",
      filterParams: {
        page: this.currentPage,
        size: 10,
        sort: "desc",
      },
    };
  },
  mounted() {
    this.getPage(this.url, this.tokens.access_token);
  },
  watch: {
    // whenever question changes, this function will run
    currentPage(newCurrentPage) {
      this.filterParams.page = newCurrentPage;
      this.getPage(this.url, this.tokens.access_token);
    },
  },
  methods: {
    getPage(url, token) {
      const { isFetching, data, onFetchError, onFetchResponse } = useFetch(
        url,
        {
          beforeFetch({ options }) {
            options.headers.Authorization = `Bearer ${token}`;

            return { options };
          },
        }
      ).get();

      onFetchError((error) => {
        this.error = error.message;
      });

      onFetchResponse(() => {
        this.usersPage = JSON.parse(data.value);
      });
      return { isFetching };
    },
    updateHandler(newFilter) {
      this.filterParams = Object.assign(newFilter, this.filterParams);
      this.getPage(this.url, this.tokens.access_token);
    },
  },
  computed: {
    url() {
      const _url = new URL(`${process.env.VUE_APP_BASE_URI}/users/all`);
      let obj = Object.assign(this.filterParams, this.customFilterParams);
      Object.keys(obj).forEach((key) =>
        obj[key] === undefined ? delete obj[key] : {}
      );
      _url.search = new URLSearchParams(obj);
      return _url.toString();
    },
  },
};
</script>
  
<style>
</style>